package com.disgruntledbots;

import java.util.ArrayList;
import java.util.List;

import org.andengine.engine.handler.IUpdateHandler;
import org.andengine.extension.physics.box2d.PhysicsWorld;

import com.badlogic.gdx.physics.box2d.Body;
import com.badlogic.gdx.physics.box2d.Contact;

public class ScoreKeeperUpdateHandler implements IUpdateHandler {

	MultiplayerActivity parent;
	ArrayList<PhysicsEntityConnector> mObjects;
	PhysicsWorld pWorld;
	
	public ScoreKeeperUpdateHandler(MultiplayerActivity parent)
	{
		this.parent = parent;
		mObjects = parent.physicsObjects;
		this.pWorld = parent.physicsWorld;
	}
	
	
	@Override
	public void onUpdate(float pSecondsElapsed) {
		ArrayList<PhysicsEntityConnector> dispose = new ArrayList<PhysicsEntityConnector>();
		
		//this.assessCollisions(pWorld.getContactList());
		
		for(PhysicsEntityConnector p : mObjects)
		{
			try{
				if(p.getClass() == DamageablePhysicsEntity.class)
				{
					try{
						DamageablePhysicsEntity d = (DamageablePhysicsEntity)p;
						if(d.mHealth <= 0)
						{
							parent.score += d.mPoints;
							d.dispose();
							dispose.add(d);
						}
					}catch(ClassCastException cce)
					{
						
					}
				}
			}catch(NullPointerException e)
			{
				
			}
		}
		synchronized(this){
			mObjects.removeAll(dispose);
		}
		
		mObjects.trimToSize();
	}

	@Override
	public void reset() {
		// TODO Auto-generated method stub

	}
	
	private void assessCollisions(List<Contact> collisions)
	{
		DamageablePhysicsEntity bodyA;
		DamageablePhysicsEntity bodyB;
		
		for(Contact contact : collisions)
		{
			if(contact.isTouching()){
				if(contact.getFixtureA().getBody().getLinearVelocity().len() > 1f || contact.getFixtureA().getBody().getLinearVelocity().len() > 1f)
				{
					bodyA = this.findConnector(contact.getFixtureA().getBody());
					bodyB = this.findConnector(contact.getFixtureB().getBody());

					if(bodyA != null)
					{
						bodyA.recieveDamage(contact.getFixtureB().getBody());
					}

					if(bodyB != null)
					{
						bodyB.recieveDamage(contact.getFixtureA().getBody());
					}
				}
			}
		}	
	}
	
	private DamageablePhysicsEntity findConnector(Body b)
	{
		for(PhysicsEntityConnector p : mObjects)
		{
			if(p != null)
			{
				if(p.mBody == b)
				{
					if(p.getClass() == DamageablePhysicsEntity.class )
					{
						return (DamageablePhysicsEntity) p;
					}
				}
			}
		}
		
		return null;
	}

}
